<?php

namespace App\Http\Controllers\usercontroller;
use App\Constant\ApiUrl;
use App\Http\Controllers\Controller;
use Auth;
use Inertia\Inertia;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Models\DawnUser;
use Illuminate\Http\Request;
use App\Services\UserServiceInterface;
use App\Pojo\Response;
class UserController extends Controller{

    private $userService;

    public function __construct(UserServiceInterface $userService)
    {
        $this->userService = $userService;
    }
 


    // 注册用户主页 负责跳转页面 可做后续扩展
    public function registerIndex(){
        return Inertia::render("login/Register");
    }
    
    // 登录用户主页 负责跳转页面 可做后续扩展
    public function loginIndex(){
        if(Auth::check()){
            Log::info("已经登录了");
            return redirect("/dawn/dashboard/home");
        }
        return Inertia::render("login/Login");
    }

    /**
     * 用户注册
     * @return void
     */
    public function createUser(Request $request){
        $credentials = $request->validate([
            'username' => ['required'],
            'password' => ['required'],
            'confirmPassword' => ['required', "same:password"],
        ]);
        
        $result = $this->userService->register($credentials);
        return $result;
    }
    /**
     * 处理用户登录数据1
     * @return void
     */
    public function loginUser(Request $request){
            $credentials = $request->validate([
                'username' => ['required'],
                'password' => ['required'],
            ]);
            $result = $this->userService->login($request, $credentials);

            return $result;
    }

    public function getUserInfo(Request $request) {
        try {
            $userId = Auth::id();
            $cacheKey = "user_info:{$userId}";
            
            // 尝试从Redis获取数据
            $cachedData = Redis::get($cacheKey);
            
            if ($cachedData) {
                return Response::success(json_decode($cachedData, true), '从缓存获取成功');
            }

            // 如果缓存中没有，从数据库获取
            $user = DawnUser::with('zhjyUser')
                ->where('dawn_id', $userId)
                ->first();

            if (!$user) {
                return Response::error('用户不存在', 404);
            }

            $data = [
                'base_info' => [
                    'dawn_id' => $user->dawn_id,
                    'dawn_name' => $user->dawn_name,
                    'dawn_createTime' => $user->dawn_createTime,
                    'dawn_lastTime' => $user->dawn_lastTime,
                    'dawn_Status' => $user->dawn_Status
                ],
                'zhjy_info' => $user->zhjyUser ? [
                    'dawn_zhjyUser' => $user->zhjyUser->dawn_zhjyUser,
                    'dawn_zhjyAvatar' => ApiUrl::$baseApiUrl.$user->zhjyUser->dawn_zhjyAvatar,
                    'dawn_zhjyEmail' => $user->zhjyUser->dawn_zhjyEmail,
                    'dawn_zhjyPhone' => $user->zhjyUser->dawn_zhjyPhone,
                    'dawn_zhjyIdName' => $user->zhjyUser->dawn_zhjyIdName,
                    'dawn_zhjySex' => $user->zhjyUser->dawn_zhjySex,
                    'dawn_zhjyIStudentId' => $user->zhjyUser->dawn_zhjyIStudentId,
                    'dawn_zhjyDeptName' => $user->zhjyUser->dawn_zhjyDeptName,
                    'dawn_zhjyEnrollmentYear' => $user->zhjyUser->dawn_zhjyEnrollmentYear,
                    'dawn_zhjyStatus' => $user->zhjyUser->dawn_zhjyStatus
                ] : null
            ];

            // 将数据存入Redis，设置过期时间为1分钟
            Redis::setex($cacheKey, 60*60*24, json_encode($data));

            return Response::success($data, '获取成功');
        } catch (\Exception $e) {
            return Response::error('服务器错误：' . $e->getMessage(), 500);
        }
    }

    

    /**
     * 将用户从应用程序中登出。
     */
    public function logout(Request $request) {
        $result = $this->userService->logout($request);
        return $result;

        }
    }